<?php
/**
 * 提货报表
 * (model)
 */
namespace App\Models\Shipping;

use App\Models\Product\ProductClassify;
use App\Models\Basics\SysArea;
use App\Models\Product\ProductSku;
use Illuminate\Database\Eloquent\Model;
class SSkuReport extends Model
{
    protected $table = 's_shipping_sku';

    protected $guarded = [];

    public function area(){
        return $this->belongsTo(SysArea::class,'area_id');
    }

    public function sku(){
        return $this->belongsTo(ProductSku::class,'psku_id');
    }

    public function skuClassify(){
        return $this->hasOneThrough(
            ProductClassify::class,
            ProductSku::class,
            'id',//中间表
            'id',//目标表
            'psku_id',//当前模型
            'classify_id'//中间表
        );
    }

    /**
     * 获取提货报表日期范围
     * @param $date
     * @return array
     */
    public static function getDateRange($date){
        $dates = [];
        $day = date('j');
        if($day <= 15){
            $end = date('Y-m-01',strtotime('midnight first day of +1 month'));
            $dates[$end] = $end;
            $_end = date('Y-m-16',strtotime('midnight first day of +1 month'));
            $dates[$_end] = $_end;
        }else{
            $end = date('Y-m-01',strtotime('midnight first day of +2 month'));
            $dates[$end] = $end;
        }
        $_day = date('j',strtotime($date));
        if($_day <= 15){
            $_start = date('Y-m-01',strtotime($date));
            $dates[$_start] = $_start;
            $start = date('Y-m-16',strtotime($date));
            $dates[$start] = $start;
        }else{
            $start = date('Y-m-16',strtotime($date));
            $dates[$start] = $start;
        }
        if(strtotime($start) > strtotime($end)){
            return [$end];
        }
        $month = getMonthDiffByDateStr($start,$end);
        $num = $month - 1;
        for ($i = 1; $i <= $num; $i++){
            $_date1 = date('Y-m-01',strtotime("midnight first day of +$i month",strtotime($start)));
            $dates[$_date1] = $_date1;
            $_date2 = date('Y-m-16',strtotime("midnight first day of +$i month",strtotime($start)));
            $dates[$_date2] = $_date2;
        }
        ksort($dates);
        return array_values($dates);
    }
}
